package org.dromara.business.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dromara.business.domain.OrderForm;
import org.dromara.business.domain.ProductTable;
import org.dromara.business.domain.bo.OrderFormBo;
import org.dromara.business.domain.vo.OrderFormVo;
import org.dromara.business.mapper.OrderFormMapper;
import org.dromara.business.service.OrderFormService;
import org.dromara.business.service.ProductTableService;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 订单Service业务层处理
 *
 * @author Lion Li
 * @date 2025-01-22
 */
@RequiredArgsConstructor
@Service
public class OrderFormServiceImpl extends ServiceImpl<OrderFormMapper,OrderForm> implements OrderFormService {

    private final OrderFormMapper baseMapper;

    private final ProductTableService productTableService;

    /**
     * 查询订单
     */
    @Override
    public OrderFormVo queryById(Long orderId){
        return baseMapper.selectVoById(orderId);
    }

    /**
     * 查询订单列表
     */
    @Override
    public TableDataInfo<OrderFormVo> queryPageList(OrderFormBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<OrderForm> lqw = buildQueryWrapper(bo);
        Page<OrderFormVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询订单列表
     */
    @Override
    public List<OrderFormVo> queryList(OrderFormBo bo) {
        LambdaQueryWrapper<OrderForm> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<OrderForm> buildQueryWrapper(OrderFormBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<OrderForm> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getOrderId() != null, OrderForm::getOrderId, bo.getOrderId());
        lqw.eq(StrUtil.isNotBlank(bo.getUserId()), OrderForm::getUserId, bo.getUserId());
        lqw.eq(bo.getProductId() != null, OrderForm::getProductId, bo.getProductId());
        lqw.like(StrUtil.isNotBlank(bo.getUserName()), OrderForm::getUserName, bo.getUserName());
        lqw.like(StrUtil.isNotBlank(bo.getProductName()), OrderForm::getProductName, bo.getProductName());
        lqw.eq(bo.getPrice() != null, OrderForm::getPrice, bo.getPrice());
        lqw.eq(bo.getNumber() != null, OrderForm::getNumber, bo.getNumber());
        lqw.orderByDesc(OrderForm::getCreateTime);
        return lqw;
    }

    /**
     * 新增订单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(OrderFormBo bo) {
        OrderForm add = MapstructUtils.convert(bo, OrderForm.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setOrderId(add.getOrderId());
        }
        ProductTable table = productTableService.lambdaQuery().eq(ProductTable::getProductIdTwo, bo.getProductId()).one();
        if (table == null) {
            throw new ServiceException("产品ID无效或产品不存在");
        }

        if (table.getNumber() < bo.getNumber()) {
            throw new ServiceException("库存不足,请检查后重置");
        }
        productTableService.lambdaUpdate()
            .eq(ProductTable::getProductId,bo.getProductId())
            .set(ProductTable::getNumber,table.getNumber()-bo.getNumber())
            .update();
        return flag;
    }


    /**
     * 根据产品id回显产品名称
     */
    @GetMapping("/{id}")
    public R<String> getByProductName(@PathVariable Long id){
        return R.ok(productTableService.getProductName(id));
    }

    /**
     * 修改订单
     */
    @Override
    public Boolean updateByBo(OrderFormBo bo) {
        OrderForm update = MapstructUtils.convert(bo, OrderForm.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OrderForm entity){

    }

    /**
     * 批量删除订单
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){

        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
